package com.ludomancy.gamelib;

import java.awt.Graphics;
import java.awt.Image;

public class ImageStrip 
{
	public static final int ANCHOR_LEFT = 0;
	public static final int ANCHOR_RIGHT = 1;
	public static final int ANCHOR_TOP = 2;
	public static final int ANCHOR_BOTTOM = 4;
	public static final int ANCHOR_VCENTER = 8;
	public static final int ANCHOR_HCENTER = 16;
	
	private int rowSize = 0;
    private Image masterImage;
	public int frameWidth = 0;
	public int frameHeight = 0;
	private int frameCount = 0;


	public ImageStrip(Image image, int frameWidth, int frameHeight) 
	{
		this.frameWidth = frameWidth;
		this.frameHeight = frameHeight;
		rowSize = image.getWidth(null)/frameWidth;
		frameCount = rowSize * (image.getHeight(null)/frameHeight);
		masterImage = image;
	}
	
	public int getImageCount()
	{
		return frameCount;
	}
	
	public void paint(Graphics g, int frame, int x, int y, int anchor)
	{
		// find out in which row the frame is in
		int row = (frame/rowSize)*frameHeight;
		// find out in which cell the frame is in the row
		int cell = (frame % rowSize)*frameWidth;

		if((anchor & ANCHOR_RIGHT) != 0)
		{
			x -= frameWidth; 
		}
		else
		if((anchor & ANCHOR_HCENTER) != 0)
		{
			x -= frameWidth/2;
		}
		
		if((anchor & ANCHOR_BOTTOM) != 0)
		{
			y -= frameHeight;
		}
		else
		if((anchor & ANCHOR_VCENTER) != 0)
		{
			y -= frameHeight/2;
		}
		g.drawImage(masterImage, x, y, x+frameWidth, y+frameHeight, cell, row, cell+frameWidth, row+frameWidth, null);		
	}
	
	public void paint(Graphics g, int frame, int x, int y)
	{
		paint(g, frame, x, y, 0);
	}	
}
